package store

import (
	"context"
	"dy/internal/models"
	"dy/pkg/myTime"
	"dy/pkg/util"
	"time"

	"github.com/go-redis/redis"
	"xorm.io/xorm"
)

type FavoriteStore interface {
	Create(ctx context.Context, user *models.DyLikeRelation) (int, error)
	Get(ctx context.Context, user *models.DyLikeRelation) (*models.DyLikeRelation, bool, error)
	Update(ctx context.Context, user *models.DyLikeRelation) (int, error)
	Del(ctx context.Context, userId int) (int, error)
	Find(ctx context.Context, search map[string]interface{}, desc string, distinct string) ([]*models.DyLikeRelation, int, error)
	SetRedis(ctx context.Context, key, value string) error
}

type favorite struct {
	orm *xorm.Engine
	rd  *redis.Client
}

func (u *favorite) Create(ctx context.Context, user *models.DyLikeRelation) (int, error) {
	_, err := u.orm.Insert(user)
	if err != nil {
		return 0, err
	}
	return user.Id, nil
}

func (u *favorite) Get(ctx context.Context, user *models.DyLikeRelation) (*models.DyLikeRelation, bool, error) {
	flag, err := u.orm.Where("del = ?", 0).Get(user)
	if err != nil {
		return nil, false, err
	}
	return user, flag, nil
}
func (u *favorite) Update(ctx context.Context, user *models.DyLikeRelation) (int, error) {
	_, err := u.orm.Id(user.Id).Update(user)
	if err != nil {
		return 0, err
	}
	return user.Id, nil
}
func (u *favorite) Del(ctx context.Context, userId int) (int, error) {
	del := &models.DyLikeRelation{
		Del:     1,
		DelTime: myTime.MyTime(time.Now()),
	}
	_, err := u.orm.Id(userId).Update(del)
	if err != nil {
		return 0, err
	}
	return userId, nil
}

func (u *favorite) Find(ctx context.Context, search map[string]interface{}, desc string, distinct string) ([]*models.DyLikeRelation, int, error) {
	type userSearch struct {
		VideoId int `json:"video_id" `
		UserId  int `json:"user_id" `
	}
	userList := make([]*models.DyLikeRelation, 0)
	var param userSearch
	err := util.StructTo(&search, &param)
	if err != nil {
		return nil, 0, err
	}
	session := u.orm.Where("del = ?", 0)

	if param.VideoId != 0 {
		session = session.Where("video_id = ?", param.VideoId)
	}
	if param.UserId != 0 {
		session = session.Where("user_id = ?", param.UserId)
	}

	if distinct != "" {
		session = session.GroupBy(distinct)
	}
	count, err := session.Desc(desc).FindAndCount(&userList)
	if err != nil {
		return nil, 0, err
	}
	return userList, int(count), err
}

func (u *favorite) SetRedis(ctx context.Context, key, value string) error {
	//0表示不过期
	err := u.rd.Set(key, value, 0).Err()
	return err
}

func NewFavorite(ds *datastore) FavoriteStore {
	return &favorite{
		orm: ds.orm,
		rd:  ds.rd,
	}
}
